/**
 * 
 */
package org.gas.barapraja.proc;

import org.apache.log4j.Logger;
import org.gas.barapraja.handler.BindRequestHandler;
import org.gas.barapraja.handler.MultiMsgRequestHandler;
import org.gas.barapraja.handler.RequestHandler;
import org.gas.barapraja.handler.SingleMsgRequestHandler;

import com.logica.smpp.Data;
import com.logica.smpp.pdu.BindRequest;
import com.logica.smpp.pdu.Request;
import com.logica.smpp.pdu.Response;
import com.logica.smpp.pdu.SubmitMultiSM;
import com.logica.smpp.pdu.SubmitSM;

/**
 * @author gilang
 *
 */
public class IncomingPduProcessor extends PduProcessor {
	
	private static final Logger logger=Logger.getLogger(IncomingPduProcessor.class);
	
	private boolean bound=false;
	
	public IncomingPduProcessor() {
	
	}
	
	public IncomingPduProcessor(GasSmscSession session){
		setSession(session);
		session.setPduProcessor(this);
	}

	/* (non-Javadoc)
	 * @see org.gas.barapraja.proc.PduProcessor#clientRequest(com.logica.smpp.pdu.Request)
	 */
	@Override
	public void clientRequest(Request request) {
		Response response;
		RequestHandler handler;
		int commandId=request.getCommandId();
		int status;
		if(!bound){
			BindRequestHandler requestHandler=new BindRequestHandler(this);
			status=requestHandler.handleRequest((BindRequest)request);
			if(status==Data.ESME_ROK){
				logger.info("bound user");
			}else{
				logger.debug("failed to bound user");
			}
		}else{
			if(request.canResponse()){
				response=request.getResponse();
				switch (commandId) {
				case Data.SUBMIT_SM:
					handler=new SingleMsgRequestHandler(this);
					handler.handleRequest((SubmitSM)request);
					break;
				case Data.SUBMIT_MULTI:
					handler=new MultiMsgRequestHandler(this);
					handler.handleRequest((SubmitMultiSM)request);
					break;
				case Data.UNBIND:
					break;
				
				}
				serverResponse(response);
				if(commandId==Data.UNBIND){
					logger.info("stopping session");
					session.stop();
				}
			}else{
				
			}
		}
		
		
	}

	/* (non-Javadoc)
	 * @see org.gas.barapraja.proc.PduProcessor#clientResponse(com.logica.smpp.pdu.Response)
	 */
	@Override
	public void clientResponse(Response response) {
		logger.debug("client response: "+response.debugString());
	}

	/* (non-Javadoc)
	 * @see org.gas.barapraja.proc.PduProcessor#serverRequest(com.logica.smpp.pdu.Request)
	 */
	@Override
	public void serverRequest(Request request) {
		logger.debug("server request: "+request.debugString());
		session.sendPdu(request);
	}

	/* (non-Javadoc)
	 * @see org.gas.barapraja.proc.PduProcessor#serverResponse(com.logica.smpp.pdu.Response)
	 */
	@Override
	public void serverResponse(Response response) {
		logger.debug("server response: "+response.debugString());
		session.sendPdu(response);

	}

}
